<template>
    <div class="info-box">
        <div class="title">{{ labelText }}信息</div>
        <el-form
            class="form-box"
            ref="formInfoRef"
            v-loading="loading"
            :element-loading-text="loadingText"
            :model="formInfo"
            :rules="rules"
            :inline="false"
            scroll-to-error
            :disabled="props.disabled"
            label-position="top"
            label-width="auto">
            <el-row :gutter="60">
                <el-col :span="8">
                    <el-form-item class="id-card-item" :label="`${labelText}身份证人像面`" prop="lp_id_card_front">
                        <div class="upload-img-box">
                            <ZwUnityKitCertificateUpload
                                v-model="formInfo.lp_id_card_front"
                                :imageList="lp_id_card_front_url"
                                :limitFormat="['JPG', 'JPEG', 'BMP', 'PNG']"
                                ocrType="RESIDENT_CARD_NATIONAL_HEAD"
                                uploadLabel="上传身份证人像面"
                                :multiple="false"
                                :disabled="props.disabled"
                                uploadTips=""
                                validateTips="仅支持上传JPG、BMP、PNG格式的图片，图片大小不能超过1M"
                                @submit="getlpIdCardFront"
                                @start="onStartLoading"
                                @finished="onFinishedLoading" />
                        </div>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item class="id-card-item" :label="`${labelText}身份证国徽面`" prop="lp_id_card_back">
                        <div class="upload-img-box">
                            <ZwUnityKitCertificateUpload
                                v-model="formInfo.lp_id_card_back"
                                :imageList="lp_id_card_back_url"
                                ocrType="RESIDENT_CARD_NATIONAL_EMBLEM"
                                uploadLabel="上传身份证国徽面"
                                :limitFormat="['JPG', 'JPEG', 'BMP', 'PNG']"
                                :multiple="false"
                                :disabled="props.disabled"
                                uploadTips=""
                                validateTips="仅支持上传JPG、BMP、PNG格式的图片，图片大小不能超过1M"
                                @submit="getlpIdCardBack"
                                @start="onStartLoading"
                                @finished="onFinishedLoading" />
                        </div>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="60">
                <el-col :span="12">
                    <el-form-item label="" prop="name">
                        <div class="id-card-desc">
                            上传身份证后自动识别信息。支持JPG、BMP、PNG格式，图片大小不能超过1M。
                        </div>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="60">
                <el-col :span="8">
                    <el-form-item :label="`${labelText}姓名`" prop="lp_name">
                        <el-input
                            v-model.trim="formInfo.lp_name"
                            :placeholder="`请输入${labelText}姓名`"
                            type="text"
                            maxlength="16"
                            show-word-limit
                            clearable />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="身份证号码" prop="lp_id_card">
                        <el-input
                            v-model.trim="formInfo.lp_id_card"
                            placeholder="请输入身份证号码"
                            type="text"
                            maxlength="18"
                            show-word-limit
                            clearable />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="身份证有效期限" prop="times">
                        <ZwUnityKitDatePicker
                            v-model="formInfo.times"
                            v-model:isLongTerm="formInfo.lp_id_card_is_long"
                            type="RESIDENT" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="60">
                <el-col :span="8">
                    <el-form-item label="身份证归属地区" prop="lp_id_card_area">
                        <ZwUnityKitCascader
                            v-model="formInfo.lp_id_card_area"
                            clearable
                            placeholder="请选择身份证归属地区" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="身份证地址" prop="lp_id_card_address">
                        <el-input
                            v-model.trim="formInfo.lp_id_card_address"
                            placeholder="请输入身份证地址"
                            type="text"
                            maxlength="64"
                            show-word-limit
                            clearable />
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
    </div>
</template>
<script setup>
import { ref, reactive, computed, watch } from 'vue';

import { getRegExp } from '@/commons/utils';

const formInfoRef = ref(null);
// 是否长期有效 1-是 2-否
const isLongTerm = ref(2);

const loading = ref(false);
const loadingText = ref('');

const emit = defineEmits(['update:modelValue']);

const props = defineProps({
    modelValue: {
        type: Object,
        default: () => {}
    },
    disabled: {
        type: Boolean,
        default: false
    },
    corpMainType: {
        type: [String, Number],
        default: 1
    }
});

const formInfo = computed({
    get() {
        return props.modelValue;
    },
    set(val) {
        emit('update:modelValue', val);
    }
});

const lp_id_card_front_url = reactive({
    code: '',
    url: ''
});

const lp_id_card_back_url = reactive({
    code: '',
    url: ''
});

const labelText = computed(() => {
    if (props.corpMainType == 1) {
        return '法人';
    }
    if (props.corpMainType == 2) {
        return '经营者';
    }
    return '';
});

const checkLpName = (ruls, value, callback) => {
    if (!value) {
        return callback(new Error(`请输入${labelText.value}姓名`));
    }
    callback();
};

const checkTimes = (ruls, value = [], callback) => {
    if (!value[0] || !value[1]) {
        return callback(new Error('请选择身份证有效期限'));
    }
    if (new Date(value[0]).getTime() - new Date(value[1]).getTime() >= 0) {
        return callback(new Error('结束时间需要大于开始时间'));
    }
    if (new Date(value[1]).getTime() - new Date().getTime() < 60 * 24 * 60 * 60 * 1000) {
        return callback(new Error('结束时间距当前时间需超过60天'));
    }
    callback();
};

const rules = reactive({
    lp_id_card_front: [{ required: true, message: '请上传身份证人像面', trigger: 'change' }],
    lp_id_card_back: [{ required: true, message: '请上传身份证国徽面', trigger: 'change' }],
    lp_name: [{ required: true, validator: checkLpName, trigger: 'blur' }],
    lp_id_card: [
        { required: true, message: '请输入身份证号码', trigger: 'blur' },
        { pattern: getRegExp('idcard'), message: '身份证号码格式不正确', trigger: 'blur' }
    ],
    times: [{ required: true, validator: checkTimes, trigger: 'change' }],
    lp_id_card_area: [{ required: true, message: '请选择身份证归属地区', trigger: 'change' }],
    lp_id_card_address: [{ required: true, message: '请输入身份证地址', trigger: 'blur' }]
});

/**
 * 表单校验
 * @param {*} typeList 需要校验的字段，默认全校验
 */
const validate = async (typeList = []) => {
    if (typeList.length) {
        let errNum = 0;
        for (let i = 0; i < typeList?.length; i++) {
            try {
                await formInfoRef.value?.validateField(typeList[i]);
            } catch (err) {
                errNum++;
            }
        }
        return !errNum;
    } else {
        return await formInfoRef.value?.validate();
    }
};

/**
 * @description: 获取身份证人像面信息
 * @param {*} info
 * @return {*}
 */
const getlpIdCardFront = info => {
    formInfoRef.value?.clearValidate('lp_id_card_front');
    if (info) {
        const { name: lp_name, idNumber: lp_id_card, address: lp_id_card_address, area: lp_id_card_area } = info;
        if (lp_name && !formInfo.value.lp_name) {
            formInfo.value.lp_name = lp_name;
            formInfoRef.value?.clearValidate('lp_name');
        }
        if (lp_id_card && !formInfo.value.lp_id_card) {
            formInfo.value.lp_id_card = lp_id_card;
            formInfoRef.value?.clearValidate('lp_id_card');
        }
        if (lp_id_card_address && !formInfo.value.lp_id_card_address) {
            formInfo.value.lp_id_card_address = lp_id_card_address;
            formInfoRef.value?.clearValidate('lp_id_card_address');
        }
        if (lp_id_card_area && !formInfo.value.lp_id_card_area) {
            formInfo.value.lp_id_card_area = lp_id_card_area;
            formInfoRef.value?.clearValidate('lp_id_card_area');
        }
    }
};

/**
 * @description: 获取身份证国徽面信息
 * @param {*} info
 * @return {*}
 */
const getlpIdCardBack = info => {
    formInfoRef.value?.clearValidate('lp_id_card_back');
    if (info) {
        const { validPeriod } = info;
        if (validPeriod) {
            if (!formInfo.value.times || formInfo.value.times.filter(ite => ite).length < 2) {
                if (validPeriod.includes('长期')) {
                    formInfo.value.lp_id_card_is_long = 1;
                    const times = validPeriod.split('-')[0].replace(/\./g, '-');
                    formInfo.value.times = [times];
                } else {
                    formInfo.value.lp_id_card_is_long = 2;
                    const times = validPeriod.split('-').map(ite => ite.replace(/\./g, '-'));
                    formInfo.value.times = times;
                }
                formInfoRef.value?.clearValidate('times');
            }
        }
    }
};

const onStartLoading = () => {
    loading.value = true;
    loadingText.value = '正在识别...';
};

const onFinishedLoading = () => {
    loading.value = false;
    loadingText.value = '';
};

watch(
    () => formInfo.value?.lp_id_card_front_url,
    val => {
        if (val) {
            lp_id_card_front_url.code = formInfo.value.lp_id_card_front;
            lp_id_card_front_url.url = formInfo.value.lp_id_card_front_url;
        }
    }
);

watch(
    () => formInfo.value?.lp_id_card_back_url,
    val => {
        if (val) {
            lp_id_card_back_url.code = formInfo.value.lp_id_card_back;
            lp_id_card_back_url.url = formInfo.value.lp_id_card_back_url;
        }
    }
);

defineExpose({
    validate
});
</script>
<style lang="scss" scoped>
.el-form-item {
    margin-bottom: 24px;
}
.info-box {
    margin-bottom: 16px;
    background: #ffffff;
    .title {
        padding: 16px 24px;
        font-size: 16px;
        font-weight: 500;
        color: #333333;
        line-height: 24px;
        border-bottom: 1px solid #e9e9e9;
    }
    .form-box {
        margin: 24px 24px 0;
        .label {
            span {
                font-size: 14px;
                font-weight: 400;
                color: rgba(153, 153, 153, 0.85);
                line-height: 22px;
            }
        }
        .upload-img-box {
            width: 45%;
        }
        .id-card-item {
            margin-bottom: 0px;
            :deep(.el-form-item__error) {
                padding-top: 28px;
            }
        }
        .id-card-desc {
            padding-top: 8px;
            font-size: 12px;
            font-weight: 400;
            color: #999999;
            line-height: 17px;
        }
    }
}
</style>
